<template>
  <el-card class="domain-detection-container" v-if="$route.name.split('.')[1] === 'detection'">
    <div class="domain-detection-content">
      <h3>域名检测</h3>
      <el-alert title="为确保能够正常访问，检查入口域名和落地域名是否被微信、QQ、钉钉等平台拦截！" type="warning" show-icon>
      </el-alert>
      <el-form ref="domainDetectionForm" label-position="top" @submit.native.prevent>
        <el-form-item label="域名检测">
          <el-row :gutter="20">
            <el-col :span="15">
              <el-input v-model.trim="detectionData.queryForm.data.url" :disabled="detectionData.detecting" placeholder="请输入域名，链接或IP，端口" @keyup.enter="detectNow" clearable>
              </el-input>
            </el-col>
            <el-col :span="5">
              <el-button type="primary" :loading="detectionData.detecting" @click="detectNow">立即检测</el-button>
            </el-col>
          </el-row>
        </el-form-item>
      </el-form>
      <div class="domain-detection-result" v-if="detectionData.showResult">
        <h4 class="check-target">
          所查目标：{{ detectionData.checkTarget }}
          <el-button type="default" size="mini" :disabled="detectionData.detecting" @click="failedRecheck" icon="el-icon-refresh">失败重查</el-button>
        </h4>
        <div class="domain-detection-result-item" v-for="item in detectionData.resultClass" :key="item.name">
          <div class="domain-detection-result-label">{{ item.name }}</div>
            <div class="domain-detection-result-content">
              <div class="domain-detection-result-loop" v-for="detection in item.children" :key="detection">
                <div class="domain-detection-result-box" v-if="detection.project">
                  {{ detection.title }}：
                  <div class="domain-detection-result-state">
                    <span class="domain-detection-result-prefix" v-if="detection.img">
                      <svg class="icon-jc" aria-hidden="true">
                        <use :href="`#icon-${ detection.img }`"></use>
                      </svg>
                      <el-divider direction="vertical"></el-divider>
                    </span>
                    <div class="domain-detection-result-msg" v-loading="detection.loading" element-loading-spinner="el-icon-loading">
                      <span class="secondary-text" v-if="detection.data?.code === -1">未检测</span>
                      <span :style="[200,0].includes(detection.data?.code) ? 'color:green' : 'color:red'" v-else-if="!detection.name">
                        {{ detection.data.msg }}
                      </span>
                      <span v-else>
                        <span v-if="item.name === '域名类' && detection.name === 'Name_Server'">
                          {{ detection.data.msg[0] }}
                          <el-divider direction="vertical"></el-divider>
                          {{ detection.data.msg[1] }}
                        </span>
                        <span v-else>{{ detection.data.msg ? detection.data.msg : '未知' }}</span>
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
        </div>
      </div>
    </div>
    <div class="domain-detection-bottom">
      <h4>检测说明</h4>
      <p>
        1. 所有检测功能均对接官方口，数据准确率达到99.99%<br>
        2. 域名检测为图标化分类预览，更有利于分享，了解域名链接全面信息<br>
        3. 注：综合检测一次扣除点数很多，请注意用量<br>
        4. 需要检测域名过多，点击<el-link type="primary" @click.prevent="routerSwitch('batch','/domain-detection/batch')">批量域名检测</el-link><br>
        5. 要跳转技术提供<br>
        6. <el-link type="primary" @click.prevent="routerSwitch('token','/user-account/user-setting')">Token对接</el-link>
      </p>
    </div>
  </el-card>
  <router-view v-else></router-view>
</template>

<script setup>
import '@/assets/icon/iconfont_ymjc.js'
import { getMonitorRel } from '@/axios/userRequest'
import { reactive, getCurrentInstance } from 'vue'
import { onBeforeRouteLeave, useRouter } from 'vue-router'
import store from '@/store/Store'
const { proxy } = getCurrentInstance()
const router = useRouter()
// 域名检测数据
const detectionData = reactive({
  resultClass:[
    {
      name: '安全类',
      children: [
        { title: 'QQ检测', project: 'qq', img: 'QQ', data: {}},
        { title: '微信检测', project: 'vx', img: 'weixin', data: {}},
        { title: '抖音检测', project: 'dyjc', img: 'douyin', data: {}},
        { title: '百度检测', project: 'baidusafe', img: 'baidu', data: {}},
        { title: '被墙污染检测', project: 'qiang', img: 'beiqiangjiance', data: {}},
        { title: '360安全检测', project: 'qihu360', img: 'icon-360', data: {}},
        { title: '域名hold检测', project: 'domainholdjc', img: 'hold', data: {}},
        { title: '绿标检测', project: 'gl', img: 'anquan', data: {}},
        { title: '微博检测', project: 'wbjc', img: 'weibo', data: {}},
        { title: '小米检测', project: 'mi', img: 'xiaomi', data: {}},
        { title: '连信检测', project: 'lianxincheck', img: 'lianxinxi', data: {}},
        { title: '多闪检测', project: 'dsjc', img: 'GroupCopy', data: {}},
        { title: '二级不死检测', project: 'llid', img: 'ziyuan', data: {}},
        { title: '飞书检测', project: 'fsjc', img: 'feishu', data: {}},
        { title: '金山检测', project: 'jinshan', img: 'kingsoft', data: {}},
        { title: '安全联盟检测', project: 'anquanjc', img: 'anquanlianmengrenzheng', data: {}},
        { title: '中网可信检测', project: 'znet', img: 'zhongwangyunzhantubiao-01', data: {}},
        { title: '谷歌检测', project: 'googlechrome', img: 'guge', data: {}},
        { title: '搜狗检测', project: 'sogoujc', img: 'sogou', data: {}},
        { title: '知乎检测', project: 'zhjc', img: 'zhihu', data: {}},
        { title: '简书检测', project: 'jianshu', img: 'jianshu', data: {}},
      ]
    },
    {
      name: '域名类',
      children: [
        { title: 'whois', project: 'whois', img: 'yuming', data: {} },
        { title: '所有者', name: 'Registrant', img: 'yuming', data: {} },
        { title: '所有者邮箱', name: 'Registrant_Email', img: 'yuming', data: {} },
        { title: '服务商', name: 'Registrar', img: 'yuming', data: {} },
        { title: '注册时间', name: 'Registration_Date', img: 'yuming', data: {} },
        { title: '到期时间', name: 'Expiration_Date', img: 'yuming', data: {} },
        { title: '域名状态', name: 'Domain_Status', img: 'yuming', data: {} },
        { title: 'DNS服务器', name: 'Name_Server', img: 'yuming', data: {} },
      ]
    },
    {
      name: '备案资质类',
      children: [
        { title: 'ICP备案', project: 'icp', img: 'beian', data: {} },
        { title: '备案号', name: 'serviceLicence', data: {} },
        { title: '备案主体', name: 'unitName', data: {} },
        { title: '备案类型', name: 'natureName', data: {} },
        { title: '审核时间', name: 'updateRecordTime', data: {} },
        { title: '网安备案', project: 'wangan', img: 'gonganxitong', data: {} },
        { title: '网站名', name: 'siteName', data: {} },
        { title: '备案号', name: 'BeianName', data: {} },
        { title: '备案主体', name: 'unitName', data: {} },
        { title: '网站类型', name: 'type', data: {} },
        { title: '审核地', name: 'BeianAddr', data: {} },
        { title: '审核时间', name: 'BeianTime', data: {} },
        { title: '管局黑名单检测', project: 'icpblack', img: 'heimingdan', data: {} },
        { title: '阿里云备案', project: 'aliyun', img: 'aliyun', data: {} },
        { title: '腾讯云备案', project: 'tencent', img: 'tengxunyun-chanyezhibianyunqiweilai', data: {} },
        { title: '百度云备案', project: 'baidu', img: 'baiduyunguanli', data: {} },
        { title: '西部数码备案', project: 'west', img: 'west', data: {} },
        { title: '景安备案', project: 'zzidc', img: 'changjinganfangjiance', data: {} },
      ]
    },
    {
      name: '网络类',
      children: [
        { title: '链接状态检测', project: 'httpcode', img: 'fuwulianjiezhuangtai', data: {} },
        { title: 'Ping检测', project: 'ping', img: 'ping', data: {} },
        { title: '延迟', name: 'ping_avg', data: {} },
        { title: 'IP地址', name: 'ip', data: {} },
        { title: '所在地', name: 'server_address', data: {} },
        { title: 'CNAME', name: 'cname', data: {} },
        { title: '端口Ping检测', project: 'tcping', img: 'ping', data: {} },
        { title: '延迟', name: 'ping_avg', data: {} },
        { title: 'IP地址', name: 'ip', data: {} },
        { title: '所在地', name: 'server_address', data: {} },
      ]
    },
    {
      name: '索引收录类',
      children: [
        { title: '百度PC收录检测', project: 'baiduincluded', img: 'baidu', data:{} },
        { title: '360PC收录检测', project: 'soincluded', img: 'icon-360', data:{} },
        { title: '搜狗PC收录检测', project: 'sogouincluded', img: 'sogou', data:{} },
        { title: '谷歌PC收录检测', project: 'googleincluded', img: 'guge', data:{} },
      ]
    }
  ],
  queryForm:{
    data: {
      token: store.state.userStore.token,
      url: '',
    },
    api: '',
    interface_name: '',
  },
  detecting: false,// 检测中
  showResult: false,// 显示结果
  checkTarget: '',// 所查目标
  errTestArr: [],// 失败检测列表
  testTotal: 0,// 已检测的数量
  moreArr: ['whois', 'icp', 'wangan', 'ping', 'tcping'],// 有更多结果的检测接口
})
// 页面离开前
onBeforeRouteLeave((to, from, next)=>{
  if(!detectionData.detecting) return next()
  proxy.$confirm('正在进行域名综合检测，离开后检测结果将丢失，您可以直接离开或等待检测完成后再离开。','提示',{
    closeOnClickModal: false,
    customClass: 'commonMessageBox',
    cancelButtonText: '再等等',
    confirmButtonText: '确认离开',
    type: 'warning',
  }).then(()=> next())
    .catch(err=> next(false))
})
let detectionArr = detectionData.resultClass.map(item => item.children).flat()
// 立即检测
const detectNow = ()=>{
  if(!detectionData.queryForm.data.url) return proxy.$message.error('请输入要检测的域名')
  detectionData.checkTarget = detectionData.queryForm.data.url
  detectionData.detecting = true
  detectionData.errTestArr = []
  detectionData.testTotal = 0
  if(!detectionData.showResult){
    detectionData.showResult = true
    document.querySelector('.domain-detection-container').style.height = 'unset'
  }
  detectionArr.forEach(item => item.project && !item.name ? detectMethod(item,'now') : delete item.project)
}
// 失败重查
const failedRecheck = ()=>{
  if(detectionData.errTestArr.length === 0) return proxy.$message.warning('没有失败的检测。')
  detectionData.detecting = true
  detectionArr.forEach(item => detectionData.errTestArr.includes(item.project) ? detectMethod(item,'failed') : '')
}
// 检测方法封装
const detectMethod = async (item,type)=>{
  item.loading = true
  type === 'failed' || (detectionData.showResult && type === 'now') ? item.data = {} : ''
  type === 'failed' ? detectionData.queryForm.data.url = detectionData.checkTarget : ''
  detectionData.queryForm.api = `${ store.state.userStore.jcApiUrl }/${ item.project }`
  detectionData.queryForm.interface_name = item.project
  const res = await getMonitorRel(detectionData.queryForm)
  if(res.code === 0){
    item.loading = false
    type === 'now' ? detectionData.testTotal++ : ''
    if(res.data[item.project]?.code === 500 || res.data[item.project] === null){
      res.data[item.project] = { code: 500, msg: '检测失败' }
      type === 'now' ? detectionData.errTestArr.push(item.project) : ''
    }else if(type === 'failed'){
      let index = detectionData.errTestArr.indexOf(item.project)
      detectionData.errTestArr.splice(index,1)
    }
    item.data = res.data[item.project]
    detectionData.moreArr?.includes(item.project) ? moreResult(res.data[item.project],item.project) : ''
    if(res.data['qq']?.code === -1){
      proxy.$confirm('您的检测点数已用尽，请您前往<a href="https://user.urlzt.com/center/shop" target="_blank">极强检测</a>进行续费。','提示',{
        closeOnClickModal: false,
        customClass: 'commonMessageBox',
        dangerouslyUseHTMLString: true,
        type: 'warning'
      }).then(()=>{}).catch(err=>{})
    }
  }else{
    item.loading = false
    item.data = { code: 500, msg: '检测失败' }
    if(type === 'now'){
      detectionData.testTotal++
      detectionData.errTestArr.push(item.project)
    }
  }
  detectionData.testTotal === detectionArr.length-24 ? detectionData.detecting = false : ''
}
let domainArr = detectionData.resultClass[1].children
let recordArr = detectionData.resultClass[2].children
let networkArr = detectionData.resultClass[3].children
// 更多结果
const moreResult = (res, project)=>{
  if([200, 0].includes(res?.code)){
    switch (project){
      case 'whois':
        for (let i = 1; i <= 7; i++){
          if(Object.keys(res.data).includes(domainArr[i].name)){
            domainArr[i].data.msg = res.data[domainArr[i].name]
            domainArr[i].project = true
          }
        }
        break
      case 'icp':
        let icpData = res.data[0] ? res.data[0] : res.data
        for(let i = 1;i <= 4; i++){
          if(Object.keys(icpData).includes(recordArr[i].name)){
            recordArr[i].data.msg = icpData[recordArr[i].name]
            recordArr[i].project = true
          }
        }
        break
      case 'wangan':
        for (let i = 6;i <= 11; i++){
          if(Object.keys(res.data).includes(recordArr[i].name)){
            recordArr[i].data.msg = res.data[recordArr[i].name]
            recordArr[i].project = true
          }
        }
        break
      case 'ping':
        for (let i = 2; i<= 5; i++){
          if(Object.keys(res.data).includes(networkArr[i].name)){
            networkArr[i].data.msg = res.data[networkArr[i].name]
            networkArr[i].project = true
          }
        }
        break
      case 'tcping':
        for (let i = 7; i<= 9; i++){
          if(Object.keys(res.data).includes(networkArr[i].name)){
            networkArr[i].data.msg = res.data[networkArr[i].name]
            networkArr[i].project = true
          }
        }
        break
    }
  }
}
// 路由跳转
const routerSwitch = (type,url)=>{
  type === 'token' ? localStorage.setItem('switchTabSet','token') : ''
  router.push(`/user-center${url}`)
}
</script>

<style lang="less" scoped>
.domain-detection-container{
  border-radius: 52px 12px 12px;
  height: 100%;
  &:deep(.el-card__body) {
    height: 100%;
    box-sizing: border-box;
    padding: 40px 30px;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    .domain-detection-content{
      .el-alert{
        margin: 20px 0;
        color: @success;
        border-color: @success;
        background-color: @success-plain;
        .el-alert__icon{
          color:@success;
        }
      }
      .el-form{
        .el-form-item{
          .el-form-item__label{
            font-size: 16px;
            color: @title;
          }
          .el-form-item__content{
            .el-button{
              width: 140px;
              border-radius: 2px;
            }
          }
        }
      }
      .domain-detection-result{
        .check-target{
          color: @title;
          border-left: 4px solid @primary;
          padding-left: 15px;
          font-weight: bold;
          font-size: 16px;
          margin: 30px 0;
          display: flex;
          justify-content: space-between;
          align-items: center;
        }
        .domain-detection-result-item{
          display: flex;
          margin-bottom: 2px;
          .domain-detection-result-label{
            background-color: @primary-plain;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            width: 150px;
            padding-bottom: 0;
            color: @secondary;
            font-size: 14px;
          }
          .domain-detection-result-content{
            padding: 10px 20px;
            width: 100%;
            color: @title;
            .domain-detection-result-loop{
              display: inline-block;
            }
            .domain-detection-result-box{
              display: inline-flex;
              align-items: center;
              margin: 10px 20px 10px 0;
              height: 24px;
              font-size: 12px;
              .domain-detection-result-state{
                display: inline-flex;
                align-items: center;
                border: 1px solid #dcdfe6;
                height: inherit;
                border-radius: 2px;
                box-sizing: border-box;
                padding: 2px 4px;
                .domain-detection-result-prefix{
                  display: flex;
                  align-items: center;
                  .icon-jc {
                    width: 1.4em;
                    height: 1.4em;
                    vertical-align: -0.15em;
                    fill: currentColor;
                    overflow: hidden;
                  }
                  .el-divider{
                    margin: 0 5px;
                  }
                }
                .domain-detection-result-msg{
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  min-width: 13px;
                  .el-loading-mask{
                    margin-top: 14px;
                  }
                }
              }
            }
          }
        }
      }
    }
    .domain-detection-bottom{
      height: 238px;
      border-radius: 4px;
      border: 1px dashed #E0E2E5;
      padding: 20px 30px;
      box-sizing: border-box;
      margin-top: 40px;
      h4{
        font-size: 16px;
        margin-top: 0;
      }
      p{
        font-size: 14px;
        line-height: 2;
        margin: 0;
        color: @secondary;
        .el-link{
          vertical-align: unset;
        }
      }
    }
  }
}
</style>
